package frame.usermeau.service;

import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

public abstract class ServiceFrame extends JFrame{

    /**
     * 初始化方法
     * @param name
     */
    public void init(String name) {
        this.setTitle(name);
        //操作
        JPanel jPanel = showOptions();
        this.purchaseNav(jPanel);
        this.setContentPane(jPanel);
        //设置窗口
        this.setBounds(580,280,700,700);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    /**
     * 显示导航栏
     * @return
     */
    public abstract JPanel showOptions();


    /**
     * 购买产品
     * @param name      产品名称
     * @param number    购买数目
     */
    public abstract void purchase(String name, Integer number);



    /**
     * 显示购买的导航栏，固定不修改
     * @param jPanel
     */
    public void purchaseNav(JPanel jPanel) {
        JLabel jl;
        //购买
        int x = 500, y = 200;
        int yc = 70;
        //名称
        jl = new JLabel("购买产品ID:");
        jl.setSize(120,20);
        jl.setLocation(x,y);
        jPanel.add(jl);
        JTextArea name = new JTextArea();
        name.setSize(120, 20);
        name.setLocation(x,y+30);
        jPanel.add(name);
        y+=yc;

        //数目
        jl = new JLabel("购买数目(额度):");
        jl.setSize(120,20);
        jl.setLocation(x,y);
        jPanel.add(jl);
        JTextArea count = new JTextArea();
        count.setSize(120, 20);
        count.setLocation(x,y+30);
        jPanel.add(count);
        y+=yc;

        //确认
        JButton submit = new JButton("购买");
        submit.setSize(60,40);
        submit.setLocation(x,y);
        submit.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(name.getText().length() == 0 || count.getText().length() == 0) {
                    JOptionPane.showMessageDialog(null, "请输入完整内容！");
                }else if (!cal(count.getText())) {
                    JOptionPane.showMessageDialog(null, "数量请输入数字！");
                }else{
                    Integer number = Integer.parseInt(count.getText());
                    purchase(name.getText(), number);
                }
            }
        });
        jPanel.add(submit);
    }

    public static boolean cal(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

}
